package com.heima.article.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.heima.article.service.ApArticleService;
import com.heima.article.service.ArticleFreemarkerService;
import com.heima.file.service.FileStorageService;
import com.heima.model.article.pojos.ApArticle;
import com.heima.model.common.enums.WmNewsMessageConstants;
import com.heima.model.search.vos.SearchArticleVo;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@Service
public class ArticleFreemarkerServiceImpl implements ArticleFreemarkerService {
    @Autowired
    private Configuration configuration;

    @Autowired
    private FileStorageService fileStorageService;

    @Autowired
    private ApArticleService apArticleService;

    /**
     * 保存文章内容到minio
     *
     * @param article
     * @param content
     */
    @Async
    @Override
    public void uploadToMiniO(ApArticle article, String content) throws IOException, TemplateException {
        log.error("{}", article);
        log.warn("{}", content);
        //判断文章内容是否为空
        if (StringUtils.isNotBlank(content)) {
            Template template;
            StringWriter out = new StringWriter();
            template = configuration.getTemplate("article.ftl");
            //数据模型
            Map<String, Object> map = new HashMap<>();
            map.put("content", JSONArray.parseArray(content));
            template.process(map, out);
            //把html文件上传到minio中
            InputStream in = new ByteArrayInputStream(out.toString().getBytes());
            String s = fileStorageService.uploadHtmlFile("", article.getId() + ".html", in);
            //修改ap_article表,保存static_url字段
            article.setStaticUrl(s);
            apArticleService.updateById(article);

            //在保存文章以后，在es中新建索引
            createEsIndex(article, content, s);
        }
    }

    @Autowired
    private KafkaTemplate<String, String> kafkaTemplate;

    /**
     * 发送消息，创建索引
     *
     * @param article
     * @param content
     * @param s
     */
    private void createEsIndex(ApArticle article, String content, String s) {
        SearchArticleVo articleVo = new SearchArticleVo();
        BeanUtils.copyProperties(article, articleVo);
        articleVo.setContent(content);
        articleVo.setStaticUrl(s);
        kafkaTemplate.send(WmNewsMessageConstants.ART_TOPIC, JSONArray.toJSONString(articleVo));
    }
}
